package com.sloth.bear.service.impl;

import com.sloth.bear.dto.vo.FileUploadVo;
import com.sloth.bear.service.FileService;
import com.UpYun;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final UpYun upYun;
    
    /**
     * 又拍云域名前缀
     */
    private static final String UPYUN_DOMAIN = "https://oss.liufq.cn";
    
    /**
     * 支持的图片类型
     */
    private static final String[] SUPPORTED_IMAGE_TYPES = {
        "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"
    };
    
    /**
     * 最大文件大小：5MB
     */
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;

    @Override
    public FileUploadVo uploadImage(MultipartFile file) {
        // 文件校验
        validateFile(file);
        
        try {
            // 生成文件路径和名称
            String filePath = generateFilePath(file);
            
            // 上传到又拍云
            boolean result = upYun.writeFile(filePath, file.getBytes(), true);
            
            if (!result) {
                throw new RuntimeException("上传文件到又拍云失败");
            }
            
            // 构建文件URL
            String fileUrl = UPYUN_DOMAIN + filePath;
            
            // 返回上传结果
            return new FileUploadVo(
                file.getOriginalFilename(),
                fileUrl,
                file.getSize(),
                file.getContentType(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );
            
        } catch (IOException e) {
            log.error("读取上传文件失败", e);
            throw new RuntimeException("读取上传文件失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 校验上传的文件
     */
    private void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小不能超过5MB");
        }
        
        String contentType = file.getContentType();
        if (contentType == null) {
            throw new IllegalArgumentException("无法识别文件类型");
        }
        
        boolean isSupported = false;
        for (String supportedType : SUPPORTED_IMAGE_TYPES) {
            if (contentType.equals(supportedType)) {
                isSupported = true;
                break;
            }
        }
        
        if (!isSupported) {
            throw new IllegalArgumentException("不支持的文件类型，仅支持: JPG, PNG, GIF, WebP");
        }
    }
    
    /**
     * 生成文件存储路径
     * 格式: /images/2024/01/15/uuid.jpg
     */
    private String generateFilePath(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        // 获取文件扩展名
        String extension = "";
        int lastDotIndex = originalFilename.lastIndexOf('.');
        if (lastDotIndex > 0) {
            extension = originalFilename.substring(lastDotIndex);
        }
        
        // 生成日期路径
        LocalDateTime now = LocalDateTime.now();
        String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        
        // 生成唯一文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = uuid + extension;
        
        return String.format("/images/%s/%s", datePath, filename);
    }
}